﻿using System;
using System.Collections.Generic;
using System.Text;

namespace eslib.nnp5.Matchers
{
    /// <summary>
    /// \n匹配器,会去掉头部的空格和尾部\r\n
    /// </summary>
    public class NMatcher
    {
        private List<byte> buffer;


        public void inStream(byte[] buf)
        {
            foreach (var b in buf)
                inStream(b);
        }


        public void inStream(byte b)
        {
            //如果遇到\n结束，否则写入缓冲区（\n不会写入缓冲区）
            if (b == '\n')
            {
                tirm();       //去除空格,\r\n

                //通知观察者
                NMatcherMatchEvent?.Invoke(buffer.ToArray());

                //重置
                reset();
            }
            else
            {
                buffer.Add(b);
            }
        }

        private void reset()
        {
            buffer = new List<byte>();
        }

        public NMatcher()
        {
            buffer = new List<byte>();
        }


        void tirm()
        {
            if (buffer.Count < 1) return;

            //称除结尾\n
            if (buffer[buffer.Count - 1] == '\r')
            {
                buffer.RemoveAt(buffer.Count - 1);
            }

            //移除头部空格
            if (buffer.Count > 0)
            {
                while (buffer[0] == ' ')
                {
                    buffer.RemoveAt(0);
                    if (buffer.Count == 0) break;
                }
            }
        }


        /// <summary>
        /// 头部为"AT+"返回true
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static bool IsHeadAT(byte[] data)
        {
            if (data.Length < 3) return false;

            byte[] atp = new byte[] { (byte)'A', (byte)'T', (byte)'+' };
            for (int i = 0; i < 3; i++)
            {
                if (data[i] != atp[i]) return false;
            }
            return true;
        }


        /// <summary>
        /// 头部为"+"返回true
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static bool IsHeadPlus(byte[] data)
        {
            if (data.Length < 1) return false;
            return data[0] == (byte)'+';
        }


        public event NMatcherMatchEventDelegate NMatcherMatchEvent;
    }


    public delegate void NMatcherMatchEventDelegate(byte[] data);
}
